#!/bin/bash
set -e

source $(dirname $0)/version

cd $(dirname $0)/..

mkdir -p bin
cd ./cmd/rancherd

RUNTIME_TAG=$TAG
if [ ! -z $DRONE_BRANCH ] && [ -z $DRONE_TAG ];then
  RUNTIME_TAG=${DRONE_BRANCH/release\//}-${DRONE_COMMIT}
fi
echo "RUNTIME_TAG: $RUNTIME_TAG"

K8S_VERSION=$(grep 'ARG RKE2_VERSION=' ../../package/Dockerfile.runtime | sed 's/.*RKE2_VERSION=//')
go build -o ../../bin/rancherd-${ARCH} \
    -ldflags '-w -s -extldflags "-static"
    -X github.com/rancher/rke2/pkg/images.KubernetesVersion='$K8S_VERSION'-'$ARCH'
    -X github.com/rancher/rke2/pkg/images.RuntimeImageName=rancher-runtime
    -X github.com/rancher/k3s/pkg/version.Program=rke2
    -X github.com/rancher/k3s/pkg/version.Version='$RUNTIME_TAG \
    -tags "netgo osusergo selinux no_stage static_build sqlite_omit_load_extension"
if [ "$ARCH" = "amd64" ]; then
    cp ../../bin/rancherd-${ARCH} ../../bin/rancherd
fi

cd ../..
./scripts/chart/build cmd/rancherd/chart
./scripts/chart/package

sed -e "s|%{CHART_CONTENT}%|$(base64 -w0 ./bin/chart/*/rancher-${CHART_VERSION}.tgz)|g" ./scripts/rancher.yaml.tmpl > ./bin/rancher.yaml
